package cn.net.mugui.net.pc.panel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;

import com.mugui.Dui.DButton;
import com.mugui.Dui.DOptionPanel;
import com.mugui.Dui.DTextArea;
import com.mugui.Dui.DVerticalFlowLayout;
import com.mugui.base.base.Autowired;
import com.mugui.base.base.Component;

import cn.net.mugui.net.p2p.Server;
import cn.net.mugui.net.p2p.ServerAttr;
import cn.net.mugui.net.p2p.ServerManager;
import cn.net.mugui.net.pc.AppFrame;
import cn.net.mugui.net.pc.dialog.UserUpdateDialog;
import cn.net.mugui.net.pc.manager.FunctionUI;
import cn.net.mugui.net.pc.panel.view.ChatMsgView;
import cn.net.mugui.net.pc.panel.view.UserView;

@Component
public class ChatPanel extends FunctionUI {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6952658384586242160L;

	public ChatPanel() {
		setTitle("聊天室");
		setMenu_name("聊天室");
		setLayout(new BorderLayout(0, 0));

		JPanel panel = new JPanel();
		add(panel, BorderLayout.WEST);
		panel.setLayout(new BorderLayout(0, 0));

		user_list = new JPanel();
		panel.add(user_list);
		user_list.setLayout(new DVerticalFlowLayout());

		JPanel panel_6 = new JPanel();
		panel.add(panel_6, BorderLayout.NORTH);

		JLabel label_1 = new JLabel("用户列表");
		panel_6.add(label_1);

		DButton button_1 = new DButton((String) null, (Color) null);
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dialog.add();
				DOptionPanel.setD_width(400);
				DOptionPanel.setD_height(200);
				int showPanel = DOptionPanel.showPanel(ChatPanel.this, dialog, DOptionPanel.OPTION_OK_CANCEL);
				if (showPanel == DOptionPanel.AGREE) {
					addServerAttr(dialog.get());
				}
			}

		});
		button_1.setFont(new Font("Dialog", Font.BOLD, 13));
		button_1.setText("添加");
		panel_6.add(button_1);

		JPanel panel_1 = new JPanel();
		add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(new BorderLayout(0, 0));

		JPanel panel_3 = new JPanel();
		panel_1.add(panel_3, BorderLayout.SOUTH);

		JScrollPane scrollPane = new JScrollPane();

		textArea = new DTextArea();
		scrollPane.setViewportView(textArea);
		textArea.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER && alt_bool) {
					sendMsg();
				}
				alt_bool = false;
			}

			private boolean alt_bool = false;

			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ALT) {
					alt_bool = true;
				}
			}

		});
		textArea.setLayout(new BorderLayout(0, 0));

		JPanel panel_10 = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel_10.getLayout();
		flowLayout.setAlignment(FlowLayout.RIGHT);

		JLabel lblAltendter = new JLabel("alt+endter");
		panel_10.add(lblAltendter);

		DButton button = new DButton((String) null, (Color) null);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				sendMsg();
			}
		});
		button.setText("发送");
		panel_10.add(button);
		GroupLayout gl_panel_3 = new GroupLayout(panel_3);
		gl_panel_3.setHorizontalGroup(gl_panel_3.createParallelGroup(Alignment.LEADING)
				.addComponent(panel_10, GroupLayout.DEFAULT_SIZE, 566, Short.MAX_VALUE)
				.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 566, Short.MAX_VALUE));
		gl_panel_3.setVerticalGroup(gl_panel_3.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_3.createSequentialGroup()
						.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 144, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(panel_10, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
		panel_3.setLayout(gl_panel_3);

		JScrollPane panel_8 = new JScrollPane();
		panel_1.add(panel_8, BorderLayout.CENTER);
		panel_8.setHorizontalScrollBar(null);
		panel_8.getVerticalScrollBar().setUnitIncrement(20);

		chat_msg_list = new JPanel();
		chat_msg_list.setBackground(UIManager.getColor("CheckBox.background"));
		panel_8.setViewportView(chat_msg_list);
		chat_msg_list.setLayout(new DVerticalFlowLayout());

		JPanel panel_2 = new JPanel();
		add(panel_2, BorderLayout.NORTH);

		JPanel panel_7 = new JPanel();
		panel_2.add(panel_7);

		JLabel label_2 = new JLabel("默认聊天室");
		label_2.setFont(new Font("宋体", Font.BOLD, 16));
		panel_7.add(label_2);

		JPanel panel_4 = new JPanel();
		add(panel_4, BorderLayout.EAST);

		JLabel label = new JLabel("连接状态统计");
		panel_4.add(label);

	}

	protected void sendMsg() {
		String text = textArea.getText();
		try {
			textArea.getDocument().remove(0, text.length());
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
		String trim = text.trim();
		chat_msg_list.add(new ChatMsgView().bind(ServerAttr.self, trim));
		server.broadcast(trim);
		validate();
		repaint();
	}

	@Autowired
	private Server server;

	private void addServerAttr(ServerAttr serverAttr) {
		if (serverAttr == null) {
			DOptionPanel.showMessageDialog(ChatPanel.this, "无法保存，有空", "警告", DOptionPanel.OPTION_OK);
			return;
		}
		if (serverManager.get(serverAttr.getAddress()) == null) {
			// 保存这个
			serverManager.add(serverAttr.getAddress(), serverAttr);
			addServerAttr(serverManager.get(serverAttr.getAddress()));
		} else {
			serverManager.add(serverAttr.getAddress(), serverAttr);
			dataInit();
		}
	}

	private UserUpdateDialog dialog = new UserUpdateDialog();

	@Override
	public void dataInit() {
		user_list.removeAll();
		if (!serverManager.isInit()) {
			serverManager.init(null);
//			UdpServer.setDefaultReceiveListener(handle);
		}
		serverManager.entrySet().forEach(t -> {
			UserView newView = UserView.newView(t.getValue());
			newView.addActionListener(userViewActionListener);
			user_list.add(newView);
		});
		user_list.validate();
		user_list.repaint();
	}

	private ActionListener userViewActionListener = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			UserView userView = (UserView) e.getSource();
			switch (e.getID()) {
			case 1:// edit
				dialog.set(userView.getServerAttr());
				dialog.edit();
				DOptionPanel.setD_width(400);
				DOptionPanel.setD_height(250);
				int showPanel = DOptionPanel.showPanel(ChatPanel.this, dialog, DOptionPanel.OPTION_OK_CANCEL);
				if (showPanel == DOptionPanel.AGREE) {
					ServerAttr serverAttr = userView.getServerAttr();
					serverAttr.InitBean(dialog.get().get());
					userView.updateView();
					serverManager.add(serverAttr.getAddress(), serverAttr);
				}

				break;
			case 2:// remove
				ServerAttr serverAttr = userView.getServerAttr();
				serverManager.del(serverAttr.getAddress());
				user_list.remove(userView);
				user_list.validate();
				user_list.repaint();
				break;
			case 3:// update
				ServerAttr serverAttr2 = serverManager.get(userView.getServerAttr().getAddress());
				serverAttr2.setStatus(ServerAttr.status_1);
				serverManager.add(serverAttr2.getAddress(),serverAttr2);
				break;
			default:
				break;
			}
		}
	};

	@Autowired
	private ServerManager serverManager;

	@Override
	public void dataSave() {

	}

	@Autowired
	private AppFrame appFrame;
	private JPanel user_list;
	private DTextArea textArea;

	@Override
	public void init() {
		appFrame.setSize(1000, 600);
	}

	/**
	 * udpbag 处理
	 */
//	private UdpBagHandle handle = new UdpBagHandle() {
//		public boolean ping(UdpServer server, cn.net.mugui.net.udp.UdpBag resolve) {
//			ServerAttr serverAttr = new ServerAttr();
//			serverAttr.setAddress(Base58.encode(resolve.getFrom()));
//			ServerAttr serverAttr2 = manager.get(serverAttr.getAddress());
//			if (serverAttr2 == null) {
//				serverAttr.setHost(server.getTo_host()).setPort(server.getTo_port());
//				serverAttr.setName("");
//				serverAttr.setStatus(ServerAttr.status_3);
//				serverAttr.setType(ServerAttr.type_0);
//				manager.add(serverAttr.getAddress(), serverAttr);
//				addUserView(serverAttr);
//			} else {
//				serverAttr = serverAttr2;
//				serverAttr.setHost(server.getTo_host()).setPort(server.getTo_port());
//				serverAttr.setName("");
//				serverAttr.setStatus(ServerAttr.status_3);
//				serverAttr.setType(ServerAttr.type_0);
//			}
//			return true;
//		}
//
//		public boolean sucess(UdpServer server, cn.net.mugui.net.udp.UdpBag resolve) {
//			System.out.println(
//					"接受到的消息" + server.getTo_host() + " " + server.getTo_port() + " " + new String(resolve.getData()));
//			ServerAttr serverAttr = manager.get(Base58.encode(resolve.getFrom()));
//			chat_msg_list.add(
//					new ChatMsgView().bind(serverAttr, new String(resolve.getData(), Charset.forName("UTF-8"))));
//			validate();
//			repaint();
//			return true;
//		};
//	};
	private JPanel chat_msg_list;

	public void addUserView(ServerAttr serverAttr) {
		UserView newView = UserView.newView(serverAttr);
		newView.addActionListener(userViewActionListener);
		user_list.add(newView);
		user_list.validate();
		user_list.repaint();
	};

	@Override
	public void quit() {

	}
	/**
	 * 添加一个chat消息
	 * @param serverAttr
	 * @param data
	 */
	public void addChatMsg(ServerAttr serverAttr, Object data) {
		chat_msg_list.add(
				new ChatMsgView().bind(serverAttr,data.toString()));
		validate();
		repaint();
	}

}
